//
//  LHLoginAboutViewModel.swift
//  LHWeiBo
//
//  Created by snowimba on 16/1/21.
//  Copyright © 2016年 snowimba. All rights reserved.
//

import UIKit

class LHLoginAboutViewModel: NSObject {

	var userInfo : LHUserInfo?

	var isLogin : Bool {

		if self.unarchiverUserModel() != nil {

			if self.isOverdue && self.userInfo != nil {

				return true
			}
		}
		return false
	}

	var isOverdue : Bool {

		let userInfoOld = self.unarchiverUserModel()

		if NSDate().compare((userInfoOld?.overdueDate)!) == .OrderedAscending {

			return true
		}
		return false
	}

	static let sharedViewModel : LHLoginAboutViewModel = {

		let instance = LHLoginAboutViewModel()

		instance.userInfo = instance.unarchiverUserModel()

		return instance
	}()

	private let path = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("userInfo.archive")

	func requestModelData(parametersNew: [String: AnyObject], finshBlack: (isFalse: Bool) -> ()) {

		LHSessionManager.sessionManager.request(.POST, URLString: "https://api.weibo.com/oauth2/access_token", parameters: parametersNew, finishBack: { (response, error) -> () in

				if error != nil {

					print(error)

					finshBlack(isFalse: false)

					return
				}

				let dict: [String: AnyObject] = response as! [String: AnyObject]
				let userInfoOld = LHUserInfo(dict: dict)

				self.requestUserInfo(userInfoOld, finshBlack: finshBlack)
//				let path = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("userInfo.archive")
//				NSKeyedArchiver.archiveRootObject(userInfo, toFile: path)
			})
	}

	private func requestUserInfo(userInfoOld: LHUserInfo, finshBlack: (isFalse: Bool) -> ()) {

//        https://api.weibo.com/2/users/show.json

		let URLString = "https://api.weibo.com/2/users/show.json?access_token=\(userInfoOld.access_token!)&uid=\(userInfoOld.uid!)"

		LHSessionManager.sessionManager.request(URLString: URLString, parameters: nil, finishBack: { (response, error) -> () in

				if error != nil {

					print(error)
					finshBlack(isFalse: false)
					return
				}

				let dict: [String: AnyObject] = response as! [String: AnyObject]
				userInfoOld.screen_name = dict["screen_name"] as? String
				userInfoOld.avatar_large = dict["avatar_large"] as? String

				self.userInfo = userInfoOld

				self.archiverUserModel(userInfoOld)

				finshBlack(isFalse: true)
			})
	}

	func archiverUserModel(userInfoOld: LHUserInfo) {

		NSKeyedArchiver.archiveRootObject(userInfoOld, toFile: path)
	}

	func unarchiverUserModel() -> (LHUserInfo?) {

		return NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? LHUserInfo
	}
}
